<template>
  <div v-auth="'business.linked.select'">
    <div>
      <el-button v-auth="'business.linked.create'" type="primary" :icon="Plus" @click="add">添加控制</el-button>
    </div>
    <div>
      <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
        @selection-change="selectionChange" :isShowPag="false">
        <template #condition="{ row }">
          <div v-for="(item, idnex) in row.condition" :key="index">
            <el-space v-if="item.triggerType == 1">
              当触发告警{{ isNullOrEmpty( item.triggerParamDesc ) }}时
            </el-space>
            <el-space v-if="item.triggerType == 2">
              当数据{{ isNullOrEmpty( item.triggerParamDesc ) }}{{ TRIGGERCONDITIONTEXT[item.triggerTerm]?.label
              }}{{ isNullOrEmpty( item.triggerValue ) }}时
            </el-space>
            <el-space v-if="item.triggerType == 3">
              当触发事件{{ isNullOrEmpty( item.triggerParamDesc ) }}时
            </el-space>
            <el-space v-if="item.triggerType == 4">
              当触发控制时间{{ isNullOrEmpty( item.triggerParamDesc ) }}时
            </el-space>
          </div>
        </template>
        <template #control="{ row }">
          <div v-for="(item, idnex) in row.control" :key="index">
            <el-space>
              {{ isNullOrEmpty( item.commandName ) }}({{ isNullOrEmpty( item.deviceName ) }})
            </el-space>
          </div>
        </template>
        <template #action="{ row }">
          <el-space>
            <sj-link v-auth="'business.linked.update'" custom-type="sblue" :underline="false"
              @click="add(row)">编辑</sj-link>
            <sj-link v-auth="'business.linked.delete'" custom-type="sred" :underline="false"
              @click="deletes(row)">删除</sj-link>
          </el-space>
        </template>
      </pure-table>
    </div>
    <!-- <controlform
      v-model="centerDialogVisible"
      :id="editid"
      :closedilog="closedilog"
    ></controlform> -->
  </div>
</template>
<script setup lang="ts">
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import {
  addControl,
  updateControl,
  getControlDetail,
  getDeviceListops
} from "@/api/operate/device-management/control-records/index";
import { addDialog } from "@/components/ReDialog";
import {
  TRIGGERCONDITIONTEXT,
  TRIGGERTYPETEXT
} from "@/constant/device-mangenment";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  cloneDeep,
  isAllEmpty,
  deviceDetection,
  debounce
} from "@pureadmin/utils";
import { getControlList, deleteControl } from "@/api/operate/device-management/control-records/index";
import controlform from "./controlform.vue";
import { ref, reactive } from "vue";
const tableData = reactive({
  data: [],
  total: 0
});
const props = defineProps({
  deviceId: {
    type: String,
    default: ''
  },
  deviceinfo: {
    type: Object,
    default: () => { }
  }
})
const selectionData = ref([]);
const selectionChange = data => {
  selectionData.value = data;
};
const centerDialogVisible = ref(false);
const roleTableConfig = [
  { type: "selection", align: "left" },
  { prop: "id", label: "编号", width:  100 },
  { slot: "condition", label: "触发条件", minWidth: 100 },
  { prop: "delay", label: "延迟时间", minWidth: 100 },
  { slot: "control", label: "联动控制", minWidth: 100 },
  { slot: "action", label: "操作", width: 100, fixed: "right" }
];

const closedilog = type => {
  if (type == 1) {
    centerDialogVisible.value = false;
    getData();
  } else {
    centerDialogVisible.value = false;
  }
};

const getData = () => {
  getControlList({ deviceId: props.deviceId }).then(res => {
    if (res.code == 200) {
      tableData.data = res.result.data;
    }
  });
};
const editid = ref(null);
const formRef = ref(null)
const add = (row) => {
  addDialog({
    title: `添加联动控制`,
    width: "1100px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    props: {
      id: row.id ? row.id : '',
      deviceinfo: props.deviceinfo,
    },
    contentRenderer: () => h(controlform, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        deviceinfo: props.deviceinfo,
        formInline: {
          condition: [],
          control: [],
          delay: ""
        },
        id: row.id ? row.id : ''
      };
      if (row.id) {
        getControlDetail({ id: row.id })
          .then(res => {
            if (res.code == 200) {
              options.props.formInline = res.result.data;
            }
          })
          .finally(() => {
            options.props.isLoading = false;
          });
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      FormRef.validate(valid => {
        if (valid) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          console.log(formData, "222222")
          if (row.id) {
            updateControl({
              id: props.id,
              deviceId: props.deviceId,
              ...formData
            }).then(res => {
              getData()
              if (res.code == 200) {
                ElMessage.success(res.msg);
                centerDialogVisible.value = false;
                done(); // 关闭弹框
              }
            });
          } else {
            addControl({
              ...formData,
              deviceId: props.deviceId
            }).then(res => {
              getData()
              if (res.code == 200) {
                ElMessage.success(res.msg);
                centerDialogVisible.value = false;
                done(); // 关闭弹框
              }
            });
          }
        }
      });
    },

  });
};
// 删除
const deletes = row => {
  ElMessageBox.confirm(`确认删除${row ? "当前" : "选中的"}数据?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteControl({
      ids: row ? [row.id] : selectionData.value.map(item => item.id)
    }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        getData();
      }
    });
  });
};
onMounted(() => {
  getData();
});
</script>
